import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { readIgnoreFile, relative } from '@/utils/ignore'
import type { Ignore } from 'ignore'
import type { Command } from 'commander'
import type { CommandModule } from '@/types/cli'

const command: CommandModule = {
  name: ['ig', 'ignore'],
  args: ['[type]'],
  description: 'ignore info',
  action(args: [string, Command]) {
    const type = args[0]
    let ignorePath
    if (type === 'send') {
      ignorePath = ''
    } else {
      ignorePath = path.join(process.cwd(), '.gitignore')
    }

    const ig = readIgnoreFile(ignorePath, {
      defaultPattern: ['.git']
    })

    const result = read(process.cwd(), ig)

    outputIgnoreInfo(result)
  }
}

function outputIgnoreInfo(paths: string[]) {
  let info = ''

  paths.forEach((str) => {
    info += `${chalk.gray(str)}\n`
  })

  console.log(info)
}

function read(dir: string, ig: Ignore, root = dir) {
  if (!fs.existsSync(dir)) return []
  const result: string[] = []
  fs.readdirSync(dir).forEach((file) => {
    const current = path.join(dir, file)
    const relativePath = relative(current, root)
    const isIgnore = ig.ignores(relativePath)
    const isDirectory = fs.statSync(current).isDirectory()
    if (isIgnore) {
      result.push(relativePath + (isDirectory ? '/' : ''))
    }
    if (isDirectory && !isIgnore) {
      result.push(...read(current, ig, root))
    }
  })
  return result
}

export default command
